package cz.farin.mandelinka.gui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.util.Collections;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JLabel;

import cz.farin.mandelinka.BugHandle;
import cz.farin.mandelinka.Maze;
import cz.farin.mandelinka.SquareType;

public class MazeLabel extends JLabel {
	
	public static Image bugImageN = new ImageIcon(MazeLabel.class.getClassLoader().getResource("images/bugN.png")).getImage();
	public static Image bugImageE = new ImageIcon(MazeLabel.class.getClassLoader().getResource("images/bugE.png")).getImage();
	public static Image wallImage = new ImageIcon(MazeLabel.class.getClassLoader().getResource("images/wall.png")).getImage();
	
	private static final int SQUARE_SIZE = 75;
	
	private Maze maze;
	private List<BugHandle> bugs = Collections.emptyList();
	

	public Maze getMaze() {
		return maze;
	}

	public void setMaze(Maze maze) {
		this.maze = maze;		
		setPreferredSize(new Dimension(SQUARE_SIZE * maze.getSizeX(), SQUARE_SIZE * maze.getSizeY()));
		invalidate();
		repaint();		
	}
	
	public void setBugs(List<BugHandle> bugs) {
		if (bugs == null) {
			this.bugs = Collections.emptyList();
		} else {
			this.bugs = bugs;
		}
	}
	
	
	@Override
	public void paint(Graphics g) {		
		super.paint(g);
		Graphics2D g2 = (Graphics2D) g;
		
		//TOHLE by mohlo byt jako image		
		for(int y = 0; y < maze.getSizeY(); y++) {
			for(int x = 0; x < maze.getSizeX(); x++) {
				SquareType sqType = maze.get(x, y);
				//offsets
				int ox =  x * SQUARE_SIZE;
				int oy =  y * SQUARE_SIZE;
				switch (sqType) {
					case WALL:
						/*g2.setColor(Color.DARK_GRAY);
						g2.drawRect(ox, oy, SQUARE_SIZE, SQUARE_SIZE);*/
						g2.drawImage(wallImage, ox, oy, SQUARE_SIZE, SQUARE_SIZE, this);
						break;
					case PASSAGE:
					case MARK:
						g2.setColor(Color.WHITE);
						g2.drawRect(ox, oy, SQUARE_SIZE, SQUARE_SIZE);
						if (sqType == SquareType.MARK) {
							g2.drawLine(ox, oy, ox + SQUARE_SIZE, oy + SQUARE_SIZE);
						}
						break;
				}
			}			
		}
		
		//g2.setColor(Color.RED);
		for(BugHandle bh : bugs) {
			int ox =  bh.getX() * SQUARE_SIZE;
			int oy =  bh.getY() * SQUARE_SIZE;
			//g2.drawLine(ox, oy, ox + SQUARE_SIZE, oy + SQUARE_SIZE);
			switch (bh.getRotation()) {
			case E:
				g2.drawImage(bugImageE, ox, oy, SQUARE_SIZE, SQUARE_SIZE, this);
				break;
			case W:
				g2.drawImage(bugImageE, ox + SQUARE_SIZE, oy, -SQUARE_SIZE, SQUARE_SIZE, this);
				break;
			case N:
				g2.drawImage(bugImageN, ox, oy, SQUARE_SIZE, SQUARE_SIZE, this);
				break;
			case S:
				g2.drawImage(bugImageN, ox + SQUARE_SIZE, oy + SQUARE_SIZE, - SQUARE_SIZE, -SQUARE_SIZE, this);
				break;
			}
			
		}
		
		
	}
	

}
